package com.youngjun.security;

import com.youngjun.core.pojo.domain.User;
import com.youngjun.core.service.UserService;
import com.youngjun.security.service.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.select(new User().setUsername(username));
        if(user==null){
            throw new CustomAuthenticationException("用户名或密码错误");
        }
        if(!user.getIsAccountNonLocked()){
            throw new CustomAuthenticationException("账号已被锁定");
        }
        if(!user.getIsCredentialsNonExpired()){
            throw new CustomAuthenticationException("证书已过期");
        }
        if(!user.getIsAccountNonExpired()){
            throw new CustomAuthenticationException("账号已过期");
        }
        if(!user.getIsEnabled()){
            throw new CustomAuthenticationException("账号已被禁用");
        }
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getIsEnabled(),
                user.getIsAccountNonExpired(),
                user.getIsCredentialsNonExpired(),
                user.getIsAccountNonLocked(),
                Arrays.asList(new SimpleGrantedAuthority("/user/demo"))
                );
    }

    @Override
    public String loadCertificateByUsername(String username) {
        User user = userService.select(new User().setUsername(username));
        if(user!=null && user.getCertificate()!=null){
            return user.getCertificate();
        }
        return null;
    }
}
